//
//  DeviceDetailVC.m
//  xychain_DM_iOS
//
//  Created by Jpwang on 2018/5/26.
//  Copyright © 2018年 Jpwang. All rights reserved.
//

#import "DeviceDetailVC.h"
#import "DeviceSettingVC.h"
#import "PathView.h"
#import "DeviceDiskVC.h"

@interface DeviceDetailVC () {
    DeviceItem *mDeviceItem;
}

@property(weak, nonatomic) IBOutlet UIButton *backBt;
@property(weak, nonatomic) IBOutlet UILabel  *titleLb;
@property(weak, nonatomic) IBOutlet UIButton *settingBt;

@property(weak, nonatomic) IBOutlet UILabel *downloadLb;
@property(weak, nonatomic) IBOutlet UILabel *downloadBigLb;
@property(weak, nonatomic) IBOutlet UIProgressView *downloadProView;
@property(weak, nonatomic) IBOutlet UILabel *uploadLb;
@property(weak, nonatomic) IBOutlet UILabel *uploadBigLb;
@property(weak, nonatomic) IBOutlet UIProgressView *uploadProView;

@property(weak, nonatomic) IBOutlet UIImageView  *pBgIv;
@property(weak, nonatomic) IBOutlet UIImageView  *pGradientIv;
@property(weak, nonatomic) IBOutlet UILabel  *profitLb;
@property(weak, nonatomic) IBOutlet UIButton *statusBt;
@property(weak, nonatomic) IBOutlet UIButton *profitBt;

@property(weak, nonatomic) IBOutlet UIImageView  *hBgIv;
@property(weak, nonatomic) IBOutlet UIImageView  *hGradientIv;
@property(weak, nonatomic) IBOutlet PathView  *progressView;
@property(weak, nonatomic) IBOutlet UILabel  *progressLb;
@property(weak, nonatomic) IBOutlet UILabel  *hardwareNameLb;
@property(weak, nonatomic) IBOutlet UILabel  *hardwareLb;
@property(weak, nonatomic) IBOutlet UIButton *hardwareBt;
@property(weak, nonatomic) IBOutlet UIImageView *noDiskIv;
@property(weak, nonatomic) IBOutlet UILabel *noDiskLb;
@property(weak, nonatomic) IBOutlet UIImageView *arrowIv;

@property(weak, nonatomic) IBOutlet UIImageView  *dBgIv;
@property(weak, nonatomic) IBOutlet UIImageView  *dGradientIv;
@property(weak, nonatomic) IBOutlet UILabel  *deviceLb;
@end

@implementation DeviceDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self requestData];
    [self updateView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setData:(DeviceItem *)deviceItem {
    mDeviceItem = deviceItem;
}

- (void)initView {
    self.pBgIv.layer.cornerRadius = globalRadius;
    self.pGradientIv.image = createGradientImage(self.pGradientIv.frame.size, colorWithString(@"#bd4097"), colorWithString(@"#db53a4"), 1);
    self.hBgIv.layer.cornerRadius = globalRadius;
    self.hGradientIv.image = createGradientImage(self.hGradientIv.frame.size, colorWithString(@"#2dff9e"), colorWithString(@"#15c1ff"), 1);
    self.dBgIv.layer.cornerRadius = globalRadius;
    self.dGradientIv.image = createGradientImage(self.dGradientIv.frame.size, colorWithString(@"#2dff9e"), colorWithString(@"#15c1ff"), 1);
    
    [[self.backBt rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    void (^block)(void) = ^ {
        NSString *title = nil;
        NSString *msg = nil;
        DeviceState *state = self->mDeviceItem.deviceState;
        if (self->mDeviceItem.deviceOnlineState && [self->mDeviceItem.deviceOnlineState intValue] == 0) {
            title = @"设备离线";
            msg = @"\n1、请检查设备是否开机；\n2、请检查设备的网络是否畅通";
        } else if (state) {
            if (!state.disks || (state.disks && state.disks.count<=0)) {
                title = @"磁盘未接入";
                msg = @"\n请检查硬盘是否正常接入";
            }else if ([state.miningState intValue]== 1) {
                
            } else if ([state.miningSwitch intValue] == 0) {
                title = @"挖矿未开启";
                msg = @"\n1、请检查是否已开启挖矿功能；\n2、数据上报延迟，更改路由状态后，状态可能延迟数分钟，请稍后查看";
            } else {
                title = @"挖矿故障";
                msg = @"\n1、请检查硬盘格式是否为ext4格式。如果格式不正确，请进行格式化操作；\n2、请检查设备的网络是否通畅；\n3、数据上报延迟，更改路由状态后，状态可能延迟数分钟，请稍后查看";
            }
        } else {
            title = @"未知错误";
            msg = @"\n1、数据上报延迟，更改路由状态后，状态可能延迟数分钟，请稍后查看\n2、请检查设备的网络是否畅通；\n3、请检查硬盘是否正常接入；\n4、如以上原因均不是，请尝试重启设备，并等待数分钟后查看；\n5、如重启设备仍无法正常工作，请联系客服人员为您查看";
        }
        if (msg) {
            UIAlertController *vc = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
            [vc addAction:cancel];
            [self setUIAlertController:vc MessageAlign:NSTextAlignmentJustified];
            [self presentViewController:vc animated:YES completion:nil];
        }
    };
    
    [[self.settingBt rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        DeviceSettingVC *vc = [storyboard instantiateViewControllerWithIdentifier:@"DeviceSettingVCID"];
        [vc setData:self->mDeviceItem];
        [self.navigationController pushViewController:vc animated:YES];
    }];
    [[self.profitBt rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        block();
    }];
    self.downloadProView.trackTintColor = colorWithString(@"#2e1c60");
    self.downloadProView.progressTintColor = colorWithString(@"#2dff9e");
    self.uploadProView.trackTintColor = colorWithString(@"#2e1c60");
    self.uploadProView.progressTintColor = colorWithString(@"#2dff9e");
    self.downloadProView.layer.cornerRadius = 6;
    self.uploadProView.layer.cornerRadius = 6;
    [[self.hardwareBt rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        if (self->mDeviceItem) {
            DeviceState *state = self->mDeviceItem.deviceState;
            if (state && state.disks && state.disks.count>0) {
                UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                DeviceSettingVC *vc = [storyboard instantiateViewControllerWithIdentifier:@"DeviceDiskVCID"];
                [vc setData:self->mDeviceItem];
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
    }];
}

- (void)updateView {
    if(!mDeviceItem) {
        return;
    }
    self.titleLb.text = mDeviceItem.label;
    DeviceState *state = mDeviceItem.deviceState;
    if (state) {
        self.downloadLb.text = [self getFriendSpeed:[state.downSpeed longValue]];
        self.downloadBigLb.text = [self getFriendSpeed:[state.downMaxSpeed longValue]];
        self.uploadLb.text = [self getFriendSpeed:[state.upSpeed longValue]];
        self.uploadBigLb.text = [self getFriendSpeed:[state.upMaxSpeed longValue]];
        self.deviceLb.text = [NSString stringWithFormat:@"在线设备：%lu台", (unsigned long)(state.clients ? state.clients.count : 0)];
        self.downloadProView.progress = [state.downSpeed longValue]*1.0/[state.downMaxSpeed longValue];
        self.uploadProView.progress = [state.upSpeed longValue]*1.0/[state.upMaxSpeed longValue];
        if (state.disks && state.disks.count>0) {
            NSString *diskName = @"";
            int total = 0;
            int used = 0;
            for (int i=0; i<state.disks.count; i++) {
                Disks *disk = state.disks[i];
                diskName = [NSString stringWithFormat:@"%@%@,", diskName, disk.diskId ? disk.diskId : @"未知"];
                total = total + (isNil(disk.storage) ? [disk.storage doubleValue] : 0);
                used = used + (isNil(disk.storageUsed) ? [disk.storageUsed doubleValue] : 0);
            }
            if (diskName.length>2) {
                diskName = [diskName substringToIndex:diskName.length-1];
            }
            float progress = (total-used)*1.0/total;
            self.hardwareNameLb.text = diskName;
            self.hardwareLb.text = [NSString stringWithFormat:@"可用空间:%dGB", (total-used)/1024];
            self.progressLb.text = [NSString stringWithFormat:@"%d%%", (int)((total-used)*1.0/total*100)];
            float end = (float)((int)(-90+360*progress));
            UIColor *color1 = colorWithString(@"#f750a7");
            UIColor *color2 = colorWithString(@"#7d3292");
            [self.progressView gradentStartAngle:-90 endAngle:end startColor:color1 endColor:color2];
            self.noDiskLb.hidden = YES;
            self.noDiskIv.hidden = YES;
            self.hardwareNameLb.hidden = NO;
            self.hardwareLb.hidden = NO;
            self.arrowIv.hidden = NO;
            self.progressView.hidden = NO;
            self.progressLb.hidden = NO;
        } else {
            self.noDiskLb.hidden = NO;
            self.noDiskIv.hidden = NO;
            self.hardwareNameLb.hidden = YES;
            self.hardwareLb.hidden = YES;
            self.arrowIv.hidden = YES;
            self.progressView.hidden = YES;
            self.progressLb.hidden = YES;
        }
    } else {
        self.downloadLb.text = @"--";
        self.downloadBigLb.text = @"--";
        self.uploadLb.text = @"--";
        self.uploadBigLb.text = @"--";
        self.hardwareLb.hidden = YES;
        self.deviceLb.text = @"在线设备：--";
        self.downloadProView.progress = 0;
        self.uploadProView.progress = 0;
        
        self.noDiskLb.hidden = NO;
        self.noDiskIv.hidden = NO;
        self.hardwareNameLb.hidden = YES;
        self.hardwareLb.hidden = YES;
        self.arrowIv.hidden = YES;
        self.progressView.hidden = YES;
        self.progressLb.hidden = YES;
    }
    CGSize size = self.statusBt.bounds.size;
    if (mDeviceItem.deviceOnlineState && [mDeviceItem.deviceOnlineState intValue] == 0) {
        [self.statusBt setTitle:@"  设备离线  " forState:UIControlStateNormal];
        [self.statusBt setBackgroundImage:createImageOfLC(size.height/2, size, colorWithString(@"#FF0000")) forState:UIControlStateNormal];
    } else if (state) {
        if (!state.disks || (state.disks && state.disks.count<=0)) {
            [self.statusBt setTitle:@"  磁盘未接入  " forState:UIControlStateNormal];
            [self.statusBt setBackgroundImage:createImageOfLC(size.height/2, size, colorWithString(@"#FF0000")) forState:UIControlStateNormal];
        } else if ([state.miningState intValue]== 1) {
            [self.statusBt setTitle:@"  正在挖矿  " forState:UIControlStateNormal];
            [self.statusBt setBackgroundImage:createImageOfLC(size.height/2, size, colorWithString(@"#15c1ff")) forState:UIControlStateNormal];
        } else if ([state.miningSwitch intValue] == 0) {
            [self.statusBt setTitle:@"  挖矿未开启  " forState:UIControlStateNormal];
            [self.statusBt setBackgroundImage:createImageOfLC(size.height/2, size, colorWithString(@"#2dff9e")) forState:UIControlStateNormal];
        } else {
            [self.statusBt setTitle:@"  挖矿故障  " forState:UIControlStateNormal];
            [self.statusBt setBackgroundImage:createImageOfLC(size.height/2, size, colorWithString(@"#FF0000")) forState:UIControlStateNormal];
        }
    } else {
        [self.statusBt setTitle:@"  未知错误  " forState:UIControlStateNormal];
        [self.statusBt setBackgroundImage:createImageOfLC(size.height/2, size, colorWithString(@"#FF0000")) forState:UIControlStateNormal];
    }
}

- (NSString *)getFriendSpeed:(long)speed {
    NSString *re = @"0Kb/";
    if (speed < 1024) {
        re = [NSString stringWithFormat:@"%ldB/s", speed];
    } else if (speed<1024*1024) {
        float f = ((float) speed)/1024.0;
        re = [NSString stringWithFormat:@"%.2fKb/s", f];
    } else {
        float f = ((float) speed)/1024.0/1024.0;
        re = [NSString stringWithFormat:@"%.2fMb/s", f];
    }
    return re;
}

- (void)requestData {
    if(!mDeviceItem) {
        return;
    }
    NSString *url = [NSString stringWithFormat:@"%@%@/state", d_detail, mDeviceItem.sn];
    [[[HttpRequest shareInstance] signGet:url map:nil] subscribeNext:^(id x) {
        if ([x[@"code"] intValue] == 200) {
            @try {
                if (x[@"data"]) {
                    NSDictionary *temp = x[@"data"];
                    NSError *error;
                    DeviceItem *deviceItem = [MTLJSONAdapter modelOfClass:[DeviceItem class] fromJSONDictionary:temp error:&error];
                    NSError *error2;
                    NSDictionary *temp2 = [temp objectForKey:@"deviceState"];
                    DeviceState *deviceState = nil;
                    NSArray *clients = nil;
                    NSArray *disk = nil;
                    RomUpgradePlan *romUpgradePlan = nil;
                    @try {
                        deviceState = [MTLJSONAdapter modelOfClass:[DeviceState class] fromJSONDictionary:temp2 error:&error2];
                    } @catch (NSException *exception) {
                        
                    }
                    NSError *error3;
                    NSError *error4;
                    if (isNil(temp2)) {
                        @try {
                            NSArray *temp3 = [temp2 objectForKey:@"clients"];
                            clients = [MTLJSONAdapter modelsOfClass:[Clinets class] fromJSONArray:temp3 error:&error3];
                            NSArray *temp4 = [temp2 objectForKey:@"disks"];
                            disk = [MTLJSONAdapter modelsOfClass:[Disks class] fromJSONArray:temp4 error:&error4];
                        } @catch (NSException *exception) {
                            
                        }
                    }
                    NSError *error5;
                    @try {
                        NSDictionary *temp5 = [temp objectForKey:@"romUpgradePlan"];
                        romUpgradePlan = [MTLJSONAdapter modelOfClass:[RomUpgradePlan class] fromJSONDictionary:temp5 error:&error5];
                    } @catch (NSException *exception) {
                        
                    }
                    if (!error) {
                        if (!error2 && deviceState) {
                            if (!error3 && clients) {
                                deviceState.clients = clients;
                            }
                            if (!error4 && disk) {
                                deviceState.disks = disk;
                            }
                            deviceItem.deviceState = deviceState;
                        }
                        if (!error5) {
                            deviceItem.romUpgradePlan = romUpgradePlan;
                        }
                        self->mDeviceItem = deviceItem;
                    }
                    [self updateView];
                }
            } @catch (NSException *exception) {
                NSLog(@"error=%@",exception);
            }
        }
    }];
    NSString *url2 = [NSString stringWithFormat:@"%@%@/yesterday_point", w_yesterday_point_device, mDeviceItem.sn];
    [[[HttpRequest shareInstance] signGet:url2 map:nil] subscribeNext:^(id x) {
        if ([x[@"code"] intValue] == 200) {
            self.profitLb.text = [NSString stringWithFormat:@"%@",x[@"data"]];
        } else {
            self.profitLb.text = @"--";
        }
    } error:^(NSError *error) {
        self.profitLb.text = @"--";
    }];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

@end
